<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'error: requests are not allowed']);
    exit;
}
$cdk = $_POST['cdk'] ?? null;
$canuse = (int)$_POST['canuse'] ?? null;
$vips = (int)$_POST['vips'] ?? null;
$words = $_POST['words'] ?? '';
if($cdk == null || $canuse == null || $vips == null) {
    echo "<script>alert('cdk failed'); window.location.href = '../../cdk.php?s=allcdk';</script>";
    exit();
}
require($_SERVER['DOCUMENT_ROOT'].'/cofd/common.php');
$sqlSelect = "SELECT 1 FROM cdk WHERE cdk = ?";
$stmt = $conn->prepare($sqlSelect);
$stmt->bind_param("s", $cdk);
if(!$stmt->execute()) {
    echo "<script>alert('cdk failed'); window.location.href = '../../cdk.php?s=allcdk';</script>";
    exit();
}
$result = $stmt->get_result();
if($result->num_rows > 0) {
    echo "<script>alert('cdk failed: This cdk has already been registered'); window.location.href = '../../cdk.php?s=allcdk';</script>";
    exit();
}
$used = 0;
$sqlInsert = "INSERT INTO cdk (`cdk`, `used`,`canuse` ,`vips`,`words`) VALUES (?,?,?,?,?)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bind_param("siiis", $cdk,$used , $canuse, $vips,$words);
if ($stmt->execute()) {
} else {
    echo "<script>alert('cdk failed'); window.location.href = '../../cdk.php?s=allcdk';</script>";
    exit();
}
$stmt->close();
$conn->close();
echo "<script>alert('cdk success'); window.location.href = '../../cdk.php?s=allcdk';</script>";